package com.lsx143.realtime.util;

import com.lsx143.realtime.annotation.NoSink;
import com.lsx143.realtime.bean.VisitorStats;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public class BeanUtil {
    /**
     * 得到类的所有变量的名称
     *
     * @param clz 类
     * @param <T> 泛型
     */
    public static <T> List<String> getFieldNames(Class<T> clz) {
        List<String> list = new ArrayList<>();
        Field[] fields = clz.getDeclaredFields();
        for (Field field : fields) {
            //被NoSink注解标注的字段不要拼接
            NoSink noSink = field.getAnnotation(NoSink.class);
            if (noSink == null) {
                String fieldName = field.getName();
                list.add(fieldName);
            }
        }
        return list;
    }

    /**
     * 返回以指定次数,以指定分割符分割的占位符字符串
     * String str=getPlaceholder("?",",",3)
     * str="?,?,?"
     *
     * @param ph         占位符
     * @param separation 分割符
     * @param phNum      占位符的个数
     * @return
     */
    public static String getPlaceholder(String ph, String separation, int phNum) {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < phNum; i++) {
            buffer.append(ph);
            if (i != phNum - 1) {
                buffer.append(separation);
            }
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        List<String> fieldNames = getFieldNames(VisitorStats.class);
        for (String fieldName : fieldNames) {
            System.out.println(fieldName);
        }

        System.out.println("0000000000000000000000000000000000");

        String join = StringUtils.join(fieldNames.toArray(), ",");
        System.out.println(join);
        System.out.println(getPlaceholder("?", ",", fieldNames.size()));
    }
}
